let http={
    oldName:"",
    ini:()=>{
        fetch(window.server+"home/ini").then(re=>{return re.json();}).then(da=>{
            document.getElementById("title_ip").innerText="IP>"+da.ip;
            document.getElementById("title_company").innerText=da.company;
            document.getElementById("title_logo").src=window.server+"material/"+da.logo+".png";
            document.getElementById("setting_logo").src=window.server+"material/"+da.logo+".png";
            document.getElementById("setting_company").value=da.company;
        })
    },
    getBaseCompany:()=>{
        fetch(window.server+"home/base/info").then(re=>{return re.json();}).then(da=>{
            document.getElementById("foot_logo").src=window.server+da.logo;
            document.getElementById("foot_name").innerHTML=da.company;
        })
    },
    /**
     * 更新公司信息
     * @param image
     * @param company
     */
    updateCompanyInfo:(image,company)=>{
        fetch(window.server+"update/company",{
            method:"POST",
            headers:{
                "Content-Type":"application/json"
            },
            body:JSON.stringify({
                "image":image,
                "company":company
            })
        }).then(res=>{return res.json();}).then(da=>{
            if(da.status){
                http.ini();
                fun.showTip("修改公司信息成功！",fun.tipSuccess);
            }else fun.showTip("修改公司信息失败！",fun.tipError);
        });
    },
    /**
     * 获取机型模板概要list
     */
    getModelSummaryList:() => {
        return fetch(window.server + "query/model/list/summary", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({})
        }).then(res => {
            return res.json();
        });
    },
    /**
     * 获取设备概要list
     */
    getEquipmentSummaryList:()=>{
        return fetch(window.server+"query/equipment/list/summary",{
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({})
        }).then(res => {
            return res.json();
        });
    },
    /**
     * 更新设备信息
     * @param type {Number} 0保存模板 ； 1保存设备
     */
    updateEquipment:(type)=> {
        let image = document.getElementById("pop_update_equipment_update_img").src;
        if (image.substring(0, 4) === "http") image = "id_"+image.substring(image.lastIndexOf("/")+1).replace(".png","");
        let name = document.getElementById("pop_update_equipment_update_name").value;
        let model = document.getElementById("pop_update_equipment_update_model").value;
        let method = document.getElementById("pop_update_equipment_method").value;
        let protocol = document.getElementById("pop_update_equipment_protocol").value;
        let path = document.getElementById("pop_update_equipment_ip_path").value;
        let a = document.getElementById("pop_update_equipment_update_alarm_kv_list");
        let alarm = [];
        for (let i = 0; i < a.childElementCount; i++) {
            let b = a.children[i];
            let b1 = b.children[0].children[0].value;
            let b2 = b.children[2].children[0];
            let b3 = b.children[3].children[0];
            if (b1.length > 0) alarm.push({"key": b1, "judge": b2.selectedIndex, "logic": b3.selectedIndex});
        }
        a = document.getElementById("pop_update_equipment_update_process_kv_list");
        let process = [];
        for (let i = 0; i < a.childElementCount; i++) {
            let b = a.children[i];
            let b1 = b.children[0].children[0].value;
            let b2 = b.children[2].children[0];
            let b3 = b.children[3].children[0];
            if (b1.length > 0) process.push({"key": b1, "judge": b2.selectedIndex, "logic": b3.selectedIndex});
        }
        a = document.getElementById("pop_update_equipment_update_await_kv_list");
        let await = [];
        for (let i = 0; i < a.childElementCount; i++) {
            let b = a.children[i];
            let b1 = b.children[0].children[0].value;
            let b2 = b.children[2].children[0];
            let b3 = b.children[3].children[0];
            await.push({"key": b1, "judge": b2.selectedIndex, "logic": b3.selectedIndex});
        }
        let speed = document.getElementById("pop_update_equipment_update_speed_kv").value;
        let program = document.getElementById("pop_update_equipment_update_program_kv").value;
        if (name.length <= 0) {
            fun.showTip("请输入设备名", fun.tipError);
            return;
        }
        if (name.length > 64) {
            fun.showTip("设备名长度需在1-64位之间", fun.tipError);
            return;
        }
        if (model.length <= 0) {
            fun.showTip("请输入机型", fun.tipError);
            return;
        }
        if (model.length > 64) {
            fun.showTip("机型名长度需在1-64位之间", fun.tipError);
            return;
        }
        if (path.length <= 0) {
            fun.showTip("请输入请求地址", fun.tipError);
            return;
        }
        if (path.length > 64) {
            fun.showTip("地址长度需在1-64位之间", fun.tipError);
            return;
        }
        if (alarm.length <= 0) {
            fun.showTip("请输入预警检测字段", fun.tipError);
            return;
        }
        if (process.length <= 0) {
            fun.showTip("请输入加工检测字段", fun.tipError);
            return;
        }
        if (await.length <= 0) {
            fun.showTip("请输入待机检测字段", fun.tipError);
            return;
        }
        if (program.length <= 0) {
            fun.showTip("请输入程序检测字段", fun.tipError);
            return;
        }
        if (speed.length <= 0) {
            fun.showTip("请输入速度检测字段", fun.tipError);
            return;
        }
        let isCreate=http.oldName.length <= 0;
        if(type===0){
            isCreate=true;
            let models=document.getElementById("pop_update_equipment_update_models");
            let model=document.getElementById("pop_update_equipment_update_model").value;
            for(let i=0;i<models.options.length;i++)if(models.options[i].value===model)isCreate=false;
        }
        fetch(window.server + "update/" + (type === 0 ? "model" : "equipment"), {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({
                "image": btoa(image),
                "name": name,
                "model": model,
                "method": method,
                "protocol": protocol,
                "url": path,
                "alarmKey": JSON.stringify(alarm),
                "processKey": JSON.stringify(process),
                "awaitKey": JSON.stringify(await),
                "programKey": program,
                "speedKey": speed,
                "oldName": http.oldName,
                "create": isCreate
            })
        }).then(res => {
            return res.json();
        }).then(da => {
            console.log(da);
            if(da.status){
                fun.showTip("保存设备信息成功",fun.tipSuccess);
                fun.closeSetting("pop_update_equipment");
                fun.closeSetting("pop_setting");
                fun.openSetting("pop_setting");
            }else fun.showTip("保存设备信息失败",fun.tipError);
        });
    },
    /**
     * 更新机型信息
     */
    updateModel:()=>{
        let image = document.getElementById("pop_update_template_update_img").src;
        if (image.substring(0, 4) === "http") image = "id_"+image.substring(image.lastIndexOf("/")+1).replace(".png","");
        let model = document.getElementById("pop_update_template_update_model").value;
        let method = document.getElementById("pop_update_model_method").value;
        let protocol = document.getElementById("pop_update_model_protocol").value;
        let a = document.getElementById("pop_update_template_update_alarm_list");
        let alarm = [];
        for (let i = 0; i < a.childElementCount; i++) {
            let b = a.children[i];
            let b1 = b.children[0].children[0].value;
            let b2 = b.children[2].children[0];
            let b3 = b.children[3].children[0];
            if (b1.length > 0) alarm.push({"key": b1, "judge": b2.selectedIndex, "logic": b3.selectedIndex});
        }
        a = document.getElementById("pop_update_template_update_process_list");
        let process = [];
        for (let i = 0; i < a.childElementCount; i++) {
            let b = a.children[i];
            let b1 = b.children[0].children[0].value;
            let b2 = b.children[2].children[0];
            let b3 = b.children[3].children[0];
            if (b1.length > 0) process.push({"key": b1, "judge": b2.selectedIndex, "logic": b3.selectedIndex});
        }
        a = document.getElementById("pop_update_template_update_await_list");
        let await = [];
        for (let i = 0; i < a.childElementCount; i++) {
            let b = a.children[i];
            let b1 = b.children[0].children[0].value;
            let b2 = b.children[2].children[0];
            let b3 = b.children[3].children[0];
            await.push({"key": b1, "judge": b2.selectedIndex, "logic": b3.selectedIndex});
        }
        let speed = document.getElementById("pop_update_template_update_speed").value;
        let program = document.getElementById("pop_update_template_update_program").value;
        if (model.length <= 0) {
            fun.showTip("请输入机型", fun.tipError);
            return;
        }
        if (model.length > 64) {
            fun.showTip("机型名长度需在1-64位之间", fun.tipError);
            return;
        }
        if (alarm.length <= 0) {
            fun.showTip("请输入预警检测字段", fun.tipError);
            return;
        }
        if (process.length <= 0) {
            fun.showTip("请输入加工检测字段", fun.tipError);
            return;
        }
        if (await.length <= 0) {
            fun.showTip("请输入待机检测字段", fun.tipError);
            return;
        }
        if (program.length <= 0) {
            fun.showTip("请输入程序检测字段", fun.tipError);
            return;
        }
        if (speed.length <= 0) {
            fun.showTip("请输入速度检测字段", fun.tipError);
            return;
        }
        let isCreate=http.oldName.length <= 0;
        fetch(window.server + "update/model", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({
                "image": btoa(image),
                "name": "",
                "model": model,
                "method": method,
                "protocol": protocol,
                "url": "",
                "alarmKey": JSON.stringify(alarm),
                "processKey": JSON.stringify(process),
                "awaitKey": JSON.stringify(await),
                "programKey": program,
                "speedKey": speed,
                "oldName": http.oldName,
                "create": isCreate
            })
        }).then(res => {
            return res.json();
        }).then(da => {
            if(da.status){
                fun.showTip("保存机型信息成功",fun.tipSuccess);
                fun.closeSetting("pop_update_model");
                fun.closeSetting("pop_setting");
                fun.openSetting("pop_setting");
            }else fun.showTip("保存机型信息失败",fun.tipError);
        });
    },
    /**
     * 获取机型详情
     */
    getModelInfo:(name)=>{
        return fetch(window.server+"query/model/info",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({"name":name})
        }).then(res=>{return res.json()});
    },
    /**
     * 获取设备详情
     * @param name
     * @return {Promise<any>}
     */
    getEquipmentInfo:(name)=>{
        return fetch(window.server+"query/equipment/info",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({"name":name})
        }).then(res=>{return res.json()});
    },
    /**
     * 删除机型
     * @param name
     */
    deleteModel:(name)=>{
        fetch(window.server+"delete/model",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({"name":name})
        }).then(res=>{return res.json()}).then(da=>{
            if(da.status){
                fun.showTip("删除机型成功",fun.tipSuccess);
                fun.closeSetting("pop_setting");
                fun.openSetting("pop_setting");
            }else fun.showTip("删除机型失败",fun.tipError);
        })
    },
    /**
     * 删除设备
     * @param name
     */
    deleteEquipment:(name)=>{
        fetch(window.server+"delete/equipment",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({"name":name})
        }).then(res=>{return res.json()}).then(da=>{
            if(da.status){
                fun.showTip("删除机型成功",fun.tipSuccess);
                fun.closeSetting("pop_setting");
                fun.openSetting("pop_setting");
            }else fun.showTip("删除机型失败",fun.tipError);
        })
    },
    /**
     * 获取报警的设备
     */
    getAlarmList:()=>{
        return fetch(window.server+"home/alarm",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({})
        }).then(res=>{return res.json()});
    },
    /**
     * 获取单个设备统计信息
     */
    getTotalEquipment:(name)=>{
        return fetch(window.server+"home/total/equipment",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({"name":name})
        }).then(res=>{return res.json()});
    },
    /**
     * 获取所有设备统计
     * @return {Promise<any>}
     */
    getTotalAll:()=>{
        return fetch(window.server+"home/total/all",{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body:JSON.stringify({})
        }).then(res=>{return res.json()});
    }
};
let fun={
    tipError:"error",
    tipSuccess:"success",
    tipNormal:"normal",
    updateTime:()=>{
        let a=new Date();
        document.getElementById("title_time").innerText=a.getFullYear()+"/"+(a.getMonth()+1)+"/"+a.getDate()+" "+a.getHours()+":"+a.getMinutes()+":"+a.getUTCSeconds();
        setTimeout(fun.updateTime,1_000);
    },
    /**
     * 更新单个机器的数据：右上角
     * @param data {{number:{'starting':number,'running',number}}}
     */
    updateCanvas1:(data)=>{
        let can=document.getElementById("canvas_one");
        can.width=can.offsetWidth;
        can.height=can.offsetHeight;
        let g=can.getContext("2d");
        g.clearRect(0,0,can.offsetWidth,can.offsetHeight);

        let vh=(window.is_pc?window.innerHeight:window.innerWidth)/100;
        let h=(can.offsetHeight-(window.is_pc?6:2)*vh)/Object.keys(data).length;
        //左侧线条
        g.strokeStyle="#2b819b88";
        g.beginPath();
        g.moveTo(h,0);
        g.lineTo(h,can.offsetHeight);
        g.stroke();
        //数据
        let top=window.is_pc?3:1;
        let num=0;
        let max=0;
        for(let k of Object.keys(data))if(data[k].starting>max)max=data[k].starting;
        g.font=h/2+"px serif";
        for(let k of Object.keys(data)){
            //日期
            g.fillStyle="#2b819b88";
            g.fillText(k,5,vh*top+h*num+h*0.7);
            //开机时间
            g.fillStyle="#1FB4CE88";
            g.fillRect(h+1,vh*top+h*num+0.1*h,(can.offsetWidth-(h+1))*(data[k].starting/max),h*0.8);
            //加工时间
            g.fillStyle="#7FD22788";
            g.fillRect(h+1,vh*top+h*num+0.1*h,(can.offsetWidth-(h+1))*(data[k].running/max),h*0.8);
            //数值显示
            g.fillStyle="#ffffff88";
            g.fillText(data[k].running+"h/"+data[k].starting+"h",h+4,vh*top+h*num+h*0.7);
            num++;
        }
    },
    /**
     * 更新所有机器的数据；底部
     * @param data {{number:{'starting':number,'running',number}}}
     */
    updateCanvas2:(data)=>{
        let can=document.getElementById("canvas_all");
        can.width=can.offsetWidth;
        can.height=can.offsetHeight;
        let g=can.getContext("2d");
        g.clearRect(0,0,can.offsetWidth,can.offsetHeight);
        let w=(can.offsetWidth)/Object.keys(data).length;
        //底部线条
        g.strokeStyle="#2b819b88";
        g.beginPath();
        g.moveTo(0,can.offsetHeight-w/2);
        g.lineTo(can.offsetWidth,can.offsetHeight-w/2);
        g.stroke();
        //数据
        let num=0;
        let max=0;
        for(let k of Object.keys(data))if(data[k].starting>max)max=data[k].starting;
        g.font=w*0.4+"px serif";
        for(let k of Object.keys(data)){
            //日期
            g.fillStyle="#2b819b88";
            g.fillText(k,w*num+w*0.5-(g.measureText(k).width/2),can.offsetHeight);
            //开机时间
            g.fillStyle="#dad943";
            g.fillRect(w*num+w*0.1,can.offsetHeight-w/2,w*0.8,-data[k].starting/max*(can.offsetHeight-w/2-1));
            //加工时间
            g.fillStyle="#33b0cc";
            g.fillRect(w*num+w*0.1,can.offsetHeight-w/2,w*0.8,-data[k].running/max*(can.offsetHeight-w/2-1));
            //数值显示
            let aa=data[k].running+"h/"+data[k].starting+"h";
            g.save();
            g.translate(w*num+w*0.64,can.offsetHeight-w*0.6);
            g.rotate(-Math.PI/2);
            g.fillStyle="#ffffff88";
            g.fillText(aa,0,0);
            g.restore();
            num++;
        }
    },
    /**
     * 更改公司logo
     */
    updateCompanyLogo:()=>{
        let a=document.createElement("input");
        a.type="file";
        a.accept=".png";
        a.click();
        a.onchange=(e)=>{
            let b=e.target;
            let f=new FileReader();
            f.onload=ee=>{
                let im=new Image();
                im.onload=eee=>{
                    if(eee.target.width>128 || eee.target.height>128){
                        fun.showTip("LOGO尺寸需小于128x128像素",fun.tipError);
                        return;
                    }
                    if(eee.target.width>=32 && eee.target>=32){
                        fun.showTip("LOGO尺寸需大于32x32像素",fun.tipError);
                        return;
                    }
                    http.updateCompanyInfo(ee.target.result,null);
                }
                im.src=ee.target.result;
            }
            f.readAsDataURL(b.files[0]);
        }
    },
    /**
     * 更改公司名
     */
    updateCompanyName:()=>{
        let name=document.getElementById("setting_company").value;
        if(name.length <= 0){
            fun.showTip("请输入公司名",fun.tipError);
            return;
        }
        if(name.length>64){
            fun.showTip("公司名长度不得超过64位",fun.tipError);
            return;
        }
        http.updateCompanyInfo(null,name);
    },
    /**
     * 添加字段
     * @param id {String} list的id
     * @param key {String} 字段名
     * @param option1 {Number} 无值/有值
     * @param option2 {Number} 或者/并且
     */
    addKeyValue:(id,key=undefined,option1=-1,option2=-1)=>{
        let n=document.createElement("div");
        n.style.marginTop="0.5vh";
        let la=document.createElement("label");
        let in1=document.createElement("input");
        in1.placeholder="字段名";
        if(key!==undefined)in1.value=key;
        la.appendChild(in1);
        n.appendChild(la);
        let p=document.createElement("p");
        p.innerText="=";
        n.appendChild(p);
        let la1=document.createElement("label");
        let se1=document.createElement("select");
        let op11=document.createElement("option");
        op11.innerText="无值";
        se1.appendChild(op11);
        let op12=document.createElement("option");
        op12.innerText="有值";
        se1.appendChild(op12);
        if(option1>-1)se1.selectedIndex=option1;
        la1.appendChild(se1);
        n.appendChild(la1);
        let la2=document.createElement("label");
        let se2=document.createElement("select");
        let op21=document.createElement("option");
        op21.innerText="或者";
        se2.appendChild(op21);
        let op22=document.createElement("option");
        op22.innerText="并且";
        se2.appendChild(op22);
        if(option2>-1)se2.selectedIndex=option2;
        la2.appendChild(se2);
        n.appendChild(la2);
        let bu=document.createElement("button");
        bu.innerText="删除";
        bu.className="button";
        bu.onclick=()=>{fun.deleteKeyValue(n);}
        if(document.getElementById(id).childElementCount>0)n.appendChild(bu);
        document.getElementById(id).appendChild(n);
    },
    /**
     * 删除字段
     * @param e {HTMLElement}
     */
    deleteKeyValue:(e)=>{
        let p=e.parentElement;
        p.removeChild(e);
    },
    /**
     * 打开设置
     */
    openSetting:async (id,name=undefined) => {
        http.oldName="";
        let a = document.getElementById(id);
        a.style.display = "block";
        let model_list = await http.getModelSummaryList();
        if(id==="pop_update_equipment"){
            let select=document.getElementById("pop_update_equipment_update_models");
            select.innerHTML="";
            for(let i=0;i<=model_list.data.length;i++){
                let op=document.createElement("option");
                op.innerText=(i===0)?"无":model_list.data[i-1].model;
                select.appendChild(op);
            }
            if(name===undefined){
                document.getElementById("pop_update_equipment_update_img").src=window.server+"material/equipment_normal.png";
                document.getElementById("pop_update_equipment_update_name").value="";
                document.getElementById("pop_update_equipment_update_model").value="";
                document.getElementById("pop_update_equipment_method").value="GET";
                document.getElementById("pop_update_equipment_protocol").value="https://";
                document.getElementById("pop_update_equipment_ip_path").value="";
                document.getElementById("pop_update_equipment_update_alarm_kv_list").innerHTML="";
                fun.addKeyValue("pop_update_equipment_update_alarm_kv_list");
                document.getElementById("pop_update_equipment_update_process_kv_list").innerHTML="";
                fun.addKeyValue("pop_update_equipment_update_process_kv_list");
                document.getElementById("pop_update_equipment_update_await_kv_list").innerHTML="";
                fun.addKeyValue("pop_update_equipment_update_await_kv_list");
                document.getElementById("pop_update_equipment_update_speed_kv").value="";
                document.getElementById("pop_update_equipment_update_program_kv").value="";
                return;
            }
            let info=await http.getEquipmentInfo(name);
            http.oldName=name;
            document.getElementById("pop_update_equipment_update_img").src=window.server+"material/"+info.image+".png";
            document.getElementById("pop_update_equipment_update_name").value=info.name;
            document.getElementById("pop_update_equipment_update_model").value=info.model;
            for(let i=0;i<select.options.length;i++)if(select.options[i].value===info.model)select.value=info.model;
            document.getElementById("pop_update_equipment_method").value=info.method;
            document.getElementById("pop_update_equipment_protocol").value=info.protocol;
            document.getElementById("pop_update_equipment_ip_path").value=info.url;
            document.getElementById("pop_update_equipment_update_alarm_kv_list").innerHTML="";
            let ks=JSON.parse(info.alarmKey);
            for(let i=0;i<ks.length;i++)fun.addKeyValue("pop_update_equipment_update_alarm_kv_list",ks[i].key,ks[i].judge,ks[i].logic);
            document.getElementById("pop_update_equipment_update_process_kv_list").innerHTML="";
            ks=JSON.parse(info.processKey);
            for(let i=0;i<ks.length;i++)fun.addKeyValue("pop_update_equipment_update_process_kv_list",ks[i].key,ks[i].judge,ks[i].logic);
            document.getElementById("pop_update_equipment_update_await_kv_list").innerHTML="";
            ks=JSON.parse(info.awaitKey);
            for(let i=0;i<ks.length;i++)fun.addKeyValue("pop_update_equipment_update_await_kv_list",ks[i].key,ks[i].judge,ks[i].logic);
            document.getElementById("pop_update_equipment_update_speed_kv").value=info.speedKey;
            document.getElementById("pop_update_equipment_update_program_kv").value=info.programKey;
        }else if(id==="pop_update_model"){
            if(name===undefined){
                document.getElementById("pop_update_template_update_img").src=window.server+"material/equipment_normal.png";
                document.getElementById("pop_update_template_update_model").value="";
                document.getElementById("pop_update_template_update_alarm_list").innerHTML="";
                fun.addKeyValue("pop_update_template_update_alarm_list");
                document.getElementById("pop_update_template_update_process_list").innerHTML="";
                fun.addKeyValue("pop_update_template_update_process_list");
                document.getElementById("pop_update_template_update_await_list").innerHTML="";
                fun.addKeyValue("pop_update_template_update_await_list");
                document.getElementById("pop_update_template_update_speed").value="";
                document.getElementById("pop_update_template_update_program").value="";
                document.getElementById("pop_update_model_method").value="GET";
                document.getElementById("pop_update_model_protocol").value="https://";
                return;
            }
            let info=await http.getModelInfo(name);
            http.oldName=name;
            console.log(info);
            document.getElementById("pop_update_template_update_img").src=window.server+"material/"+info.image+".png";
            document.getElementById("pop_update_template_update_model").value=info.model;
            document.getElementById("pop_update_template_update_alarm_list").innerHTML="";
            let qw=JSON.parse(info.alarmKey);
            for(let i=0;i<qw.length;i++)fun.addKeyValue("pop_update_template_update_alarm_list",qw[i].key,qw[i].judge,qw[i].logic);
            document.getElementById("pop_update_template_update_process_list").innerHTML="";
            qw=JSON.parse(info.processKey);
            for(let i=0;i<qw.length;i++)fun.addKeyValue("pop_update_template_update_process_list",qw[i].key,qw[i].judge,qw[i].logic);
            document.getElementById("pop_update_template_update_await_list").innerHTML="";
            qw=JSON.parse(info.awaitKey);
            for(let i=0;i<qw.length;i++)fun.addKeyValue("pop_update_template_update_await_list",qw[i].key,qw[i].judge,qw[i].logic);
            document.getElementById("pop_update_template_update_speed").value=info.speedKey;
            document.getElementById("pop_update_template_update_program").value=info.programKey;
            document.getElementById("pop_update_model_method").value=info.method;
            document.getElementById("pop_update_model_protocol").value=info.protocol;
        }else{
            let ml=document.getElementById("setting_model_list");
            ml.innerHTML="";
            for(let i=0;i<model_list.data.length;i++){
                ml.appendChild(fun.createSettingListItem(model_list.data[i].image,model_list.data[i].model,
                    new Date(model_list.data[0].timestamp).toLocaleDateString(),()=>{
                    fun.openSetting("pop_update_model",model_list.data[i].model);
                },()=>{
                    fun.openDeletePop("确认要删除 "+model_list.data[i].model+" 机型吗？",()=>http.deleteModel(model_list.data[i].model));
                }));
            }
            let equipment_list=await http.getEquipmentSummaryList();
            let el=document.getElementById("setting_equipment_list");
            el.innerHTML="";
            for(let i=0;i<equipment_list.data.length;i++){
                el.appendChild(fun.createSettingListItem(equipment_list.data[i].image,equipment_list.data[i].name,
                    equipment_list.data[i].protocol+equipment_list.data[i].url,()=>{
                    http.oldName=equipment_list.data[i].name;
                    fun.openSetting("pop_update_equipment",equipment_list.data[i].name);
                },()=>{
                    fun.openDeletePop("确认要删除 "+equipment_list.data[i].name+" 设备吗？",()=>http.deleteEquipment(equipment_list.data[i].name));
                }));
            }
        }
    },
    /**
     * 选择指定机型信息
     */
    selectModel:async () => {
        let model = document.getElementById("pop_update_equipment_update_models").value;
        if (model === "无") return;
        let info = await http.getModelInfo(model);
        document.getElementById("pop_update_equipment_update_img").src=window.server+"material/"+info.image+".png";
        document.getElementById("pop_update_equipment_update_model").value=model;
        document.getElementById("pop_update_equipment_method").value=info.method;
        document.getElementById("pop_update_equipment_protocol").value=info.protocol;
        document.getElementById("pop_update_equipment_update_alarm_kv_list").innerHTML="";
        let a=JSON.parse(info.alarmKey);
        for(let i=0;i<a.length;i++)fun.addKeyValue("pop_update_equipment_update_alarm_kv_list",a[i].key,a[i].judge,a[i].logic);
        document.getElementById("pop_update_equipment_update_process_kv_list").innerHTML="";
        a=JSON.parse(info.processKey);
        for(let i=0;i<a.length;i++)fun.addKeyValue("pop_update_equipment_update_process_kv_list",a[i].key,a[i].judge,a[i].logic);
        document.getElementById("pop_update_equipment_update_await_kv_list").innerHTML="";
        a=JSON.parse(info.awaitKey);
        for(let i=0;i<a.length;i++)fun.addKeyValue("pop_update_equipment_update_await_kv_list",a[i].key,a[i].judge,a[i].logic);
        document.getElementById("pop_update_equipment_update_speed_kv").value=info.speedKey;
        document.getElementById("pop_update_equipment_update_program_kv").value=info.programKey;
    },
    /**
     * 改变设备图片
     * @param img_id {String}
     */
    changeEquipmentImage:(img_id)=>{
        let img=document.getElementById(img_id);
        let fs=document.createElement("input");
        fs.type="file";
        fs.accept=".png";
        fs.click();
        fs.onchange=e=>{
            let f=e.target.files[0];
            if(f===undefined)return;
            let read=new FileReader();
            read.onload=ee=>{
                let im=new Image();
                im.onload=eee=>{
                    if(eee.target.width>512 || eee.target.height>512){
                        fun.showTip("图片尺寸不得超过512x512像素",fun.tipError);
                        return;
                    }
                    if(eee.target.width<96 || eee.target.height<96){
                        fun.showTip("图片尺寸不得低于96x96像素",fun.tipError);
                        return;
                    }
                    img.src=eee.target.src;
                }
                im.src=ee.target.result;
            }
            read.readAsDataURL(f);
        }
    },
    /**
     * 创建设置界面的item
     * @return {HTMLDivElement}
     */
    createSettingListItem:(image0,name0,content0,funupdate,fundelete)=>{
        let item=document.createElement("div");
        item.className="item";
        let img=document.createElement("img");
        img.src=window.server+"material/"+image0+".png";
        item.appendChild(img);
        let name=document.createElement("p");
        name.className="name";
        name.innerText=name0;
        item.appendChild(name);
        let content=document.createElement("p");
        content.className="content";
        content.innerText=content0;
        item.appendChild(content);
        let del=document.createElement("button");
        del.className="sub";
        del.innerText="删除";
        del.onclick=()=>{fundelete()};
        item.appendChild(del);
        let upd=document.createElement("button");
        upd.className="add";
        upd.innerText="编辑";
        upd.onclick=()=>{funupdate()};
        item.appendChild(upd);
        return item;
    },
    /**
     * 关闭设置
     */
    closeSetting:(id)=>{
        let a=document.getElementById(id);
        a.style.display="none";
    },
    /**
     * 关闭删除提示
     * @param e {HTMLElement}
     */
    closeDeletePop:(e)=>{
        let p=e.parentElement.parentElement.parentElement;
        document.body.removeChild(p);
    },
    /**
     * 显示提示
     * @param message
     * @param type
     */
    showTip:(message,type)=>{
        let vh=document.body.offsetHeight/100,vw=document.body.offsetWidth/100;
        let a=document.createElement("div");
        if(window.is_pc){
            a.style.padding=vh+"px";
            a.style.borderRadius=0.5*vh+"px";
        }
        else{
            a.style.padding=3*vw+"px";
            a.style.borderRadius=1.5*vw+"px";
        }
        a.style.position="fixed";
        a.style.zIndex="999";
        a.style.top="30%";
        a.style.backgroundColor="#012";
        a.style.border="solid 1px #fff8";
        let lamp=document.createElement("div");
        if(window.is_pc){
            lamp.style.width=vh+"px";
            lamp.style.height=vh+"px";
            lamp.style.borderRadius=0.5*vh+"px";
            lamp.style.marginRight=vh+"px";
        }else{
            lamp.style.width=3*vw+"px";
            lamp.style.height=3*vw+"px";
            lamp.style.borderRadius=1.5*vw+"px";
            lamp.style.marginRight=vw+"px";
        }
        lamp.style.float="left";
        if(type===fun.tipError)lamp.style.backgroundColor="red";
        else if(type===fun.tipSuccess)lamp.style.backgroundColor="green";
        else lamp.style.backgroundColor="gray";
        a.appendChild(lamp);
        let me=document.createElement("p");
        if(window.is_pc){
            me.style.fontSize=vh*1.5+"px";
            me.style.lineHeight=vh*1.5+"px";
        }else{
            me.style.fontSize=3*vw+"px";
            me.style.lineHeight=3*vw+"px";
        }
        me.style.margin="0";
        me.style.color="#fff";
        me.style.float="left";
        me.innerText=message;
        a.appendChild(me);
        document.body.appendChild(a);
        a.style.left=(document.body.offsetWidth-a.offsetWidth)/2+"px";
        let num=0,z=50,t=3,s=4;
        let move=()=>{
            a.style.top=((num<z*t)?vh*30:vh*s*(30/s+z*t-num))+"px";
            num++;
            if(vh*s*(30/s+z*t-num)<0-a.offsetHeight){
                document.body.removeChild(a);
            }else setTimeout(move,1000/z);
        }
        setTimeout(move,1000/z);
    },
    /**
     * 打开删除确认弹窗
     * @param fun
     */
    openDeletePop:(content,fun)=>{
        document.getElementById("pop_delete_content").innerText=content;
        document.getElementById("pop_delete").style.display="block";
        let a=document.getElementById("pop_delete_affirm");
        a.onclick=()=>{fun();document.getElementById("pop_delete").style.display="none";};
    },
    /**
     * 单个设备概要信息
     */
    data_equipment:{},
    /**
     * 本月所有设备信息
     */
    data_all:[],
    /**
     * 已轮播过的设备
     */
    showed_equipment:[],
    /**
     * 已轮播过的报警设备
     */
    showed_alarm:[],
    /**
     * 更新首页界面数据
     */
    updateHomePageData:async () => {
        let data_alarm = (await http.getAlarmList()).data;
        //检测报警轮播内容
        let name = "";
        for (let d in data_alarm) {
            let have = false;
            for (let n in fun.showed_alarm) if (data_alarm[d].name === fun.showed_alarm[n]) {
                have = true;
                break;
            }
            if (have) continue;
            name = data_alarm[d].name;
            break;
        }
        if (name.length === 0) {
            fun.showed_alarm = [];
            if (data_alarm.length > 0) name = data_alarm[0].name;
        }
        fun.showed_alarm.push(name);
        fun.updateHomeAlarm(name, data_alarm);
        //单个设备详情
        name = "";
        let equipment_list = (await http.getEquipmentSummaryList()).data;
        for (let d in equipment_list) {
            let have = false;
            for (let n in fun.showed_equipment) if (fun.showed_equipment[n] === equipment_list[d].name) {
                have = true;
                break;
            }
            if (have) continue;
            name = equipment_list[d].name;
            break;
        }
        if (name.length === 0) {
            fun.showed_equipment = [];
            if(equipment_list.length>0)name = equipment_list[0].name;
        }
        fun.showed_equipment.push(name);
        fun.updateHomeTotalEquipment(await http.getTotalEquipment(name));
        //全部统计
        let a=(await http.getTotalAll()).data;
        fun.updateHomeTotalAll(a);
        setTimeout(fun.updateHomePageData, 5_000);
    },
    /**
     * 更新首页预警界面
     */
    updateHomeAlarm:(name,data)=>{
        let list=document.getElementById("center_left_equipment_list");
        list.innerHTML="";
        if(name.length===0){
            document.getElementById("center_left_equipment_img_bg").style.backgroundColor="#66FF667F";
            document.getElementById("center_left_equipment_img").src=window.server+"material/equipment_normal.png";
            document.getElementById("center_left_equipment_name").innerText="无预警";
            return;
        }
        let al={};
        for(let a in data)if(data[a].name===name){
            al=data[a];
        }else{
            let div=document.createElement("div");
            div.className="list_item";
            let img=document.createElement("img");
            img.src=window.server+"material/"+data[a].image+".png";
            let p=document.createElement("p");
            p.innerText=data[a].name;
            div.appendChild(img);
            div.appendChild(p);
            list.appendChild(div);
        }
        document.getElementById("center_left_equipment_img_bg").style.backgroundColor="#FF66667F";
        document.getElementById("center_left_equipment_img").src=window.server+"material/"+al.image+".png";
        document.getElementById("center_left_equipment_name").innerText=al.name;
        console.log("预警轮播",data);
    },
    /**
     * 更新单个设备信息
     * @param data
     */
    updateHomeTotalEquipment:(data)=>{
        document.getElementById("center_right_equipment_name").innerText=data.name;
        document.getElementById("center_right_img").src=window.server+"material/"+data.image+".png";
        document.getElementById("center_right_img_bg").style.backgroundColor=(data.state.processState===0 && data.state.awaitState===0)?"#8888":(data.state.alarmState===1?"#FF66667F":(data.state.processState===1?"#33b0cc7f":"#66FF667F"));
        document.getElementById("center_right_run_speed").innerText=(data.state.speed.length>0)?data.state.speed:"无";
        document.getElementById("center_right_equipment_program").innerText=data.state.program;
        let start_time=0;
        let run_time=0;
        for(let d in data.data){
            start_time+=data.data[d].await_time+data.data[d].process_time;
            run_time+=data.data[d].process_time;
        }
        document.getElementById("center_right_starting_time").innerText=(start_time/60/60).toFixed(2)+"h";
        document.getElementById("center_right_run_time").innerText=(run_time/60/60).toFixed(2)+"h";
        document.getElementById("center_right_run_pro").innerText=(start_time===0?"0.00":(run_time/start_time*100).toFixed(2))+"%";
        let qw={};
        let today=new Date().getUTCDate();
        let num=today-7;
        if(num<0)num=0;
        for(let i=0;num+i<data.data.length && i<7;i++){
            qw[data.data[num+i].date]={
                "starting":((data.data[num+i].await_time+data.data[num+i].process_time)/60/60).toFixed(2),
                "running":(data.data[num+i].process_time/60/60).toFixed(2)
            }
        }
        fun.updateCanvas1(qw);
        console.log("单个设备概要轮播",data);
    },
    /**
     * 更新所有统计
     * @param data
     */
    updateHomeTotalAll:(data)=>{
        let start_time=0;
        let run_time=0;
        for(let d in data){
            start_time+=d.await_time+d.process_time;
            run_time+=d.process_time;
        }
        let qw={};
        for(let d in data){
            qw[data[d].date]={
                "starting":((data[d].await_time+data[d].process_time)/60/60).toFixed(2),
                "running":(data[d].process_time/60/60).toFixed(2)
            }
        }
        fun.updateCanvas2(qw);
        console.log("本月所有设备统计",data,qw);
    }
};
http.ini();
http.getBaseCompany();
fun.updateTime();
fun.updateHomePageData();
// fun.updateCanvas1({
//     16:{"starting":21.5,"running":19.5},
//     17:{"starting":23.2,"running":20.5},
//     18:{"starting":21.8,"running":19.2},
//     19:{"starting":21.6,"running":18.2},
//     20:{"starting":19.3,"running":19.1},
//     21:{"starting":22.6,"running":19.0},
//     22:{"starting":16.3,"running":16.2}
// });
// fun.updateCanvas2({
//     1:{"starting":19.8,"running":19.5},
//     2:{"starting":20.6,"running":18.3},
//     3:{"starting":15.4,"running":10.2},
//     4:{"starting":17.7,"running":9.6},
//     5:{"starting":20.2,"running":18.6},
//     6:{"starting":23.6,"running":19.5},
//     7:{"starting":22.5,"running":18.8},
//     8:{"starting":18.9,"running":17.8},
//     9:{"starting":19.2,"running":19.1},
//     10:{"starting":23.3,"running":20.5},
//     11:{"starting":15.8,"running":11.2},
//     12:{"starting":21.6,"running":18.2},
//     13:{"starting":19.3,"running":19.1},
//     14:{"starting":22.6,"running":19.0},
//     15:{"starting":22.4,"running":18.6},
//     16:{"starting":21.5,"running":19.5},
//     17:{"starting":23.2,"running":20.5},
//     18:{"starting":21.8,"running":19.2},
//     19:{"starting":21.6,"running":18.2},
//     20:{"starting":19.3,"running":19.1},
//     21:{"starting":22.6,"running":19.0},
//     22:{"starting":16.3,"running":16.2},
//     23:{"starting":0,"running":0},
//     24:{"starting":0,"running":0},
//     25:{"starting":0,"running":0},
//     26:{"starting":0,"running":0},
//     27:{"starting":0,"running":0},
//     28:{"starting":0,"running":0},
//     29:{"starting":0,"running":0},
//     30:{"starting":0,"running":0},
//     31:{"starting":0,"running":0}
// });